﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GaugeEngine.Events
{
    public class EventManager : GameComponent
    {
        private List<EventData>[] m_eventQueue;
        private int m_currentQueue;

        private Dictionary<string, EventHandlerDelegate> m_handlers;

        public EventManager(Game g) : base(g)
        {
            m_eventQueue = new List<EventData>[2];
            m_eventQueue[0] = new List<EventData>();
            m_eventQueue[1] = new List<EventData>();
            m_currentQueue = 0;

            m_handlers = new Dictionary<string, EventHandlerDelegate>();

        }

        public void QueueEvent(EventData e)
        {
            m_eventQueue[m_currentQueue].Add(e);
        }

        public void execute()
        {
            int lastQueue = m_currentQueue;
            m_currentQueue = m_currentQueue == 0 ? 1 : 0;
            foreach (EventData e in m_eventQueue[lastQueue])
            {
                if (m_handlers.ContainsKey(e.ID)) m_handlers[e.ID](e);
            }
            m_eventQueue[lastQueue].Clear();
        }

        public override void Update(GameTime dt)
        {
            execute();
        }

        public void addHandler(string id, EventHandlerDelegate d)
        {
            m_handlers.Add(id, d);
        }
    }
}
